package mil.af.amc.adpetracker.web.actions.EquipmentItem.ajax;

import mil.af.amc.adpetracker.model.EquipmentItem;
import mil.af.amc.adpetracker.service.EquipmentItemService;
import mil.af.amc.adpetracker.web.actions.AbstractAction;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Simple AJAX action to determine if an item the uer is attempting to put in the system
 * is a duplicate.
 *
 * The action results the text "true" if there is a duplicate, "false" otherwise
 *
 * @author TSgt Jason Ferguson
 */

public class CheckDuplicatesAction extends AbstractAction {

    private EquipmentItemService equipmentItemService;

    public void setEquipmentItemService(EquipmentItemService equipmentItemService) {
        this.equipmentItemService = equipmentItemService;
    }

    @Override
    public ActionForward execute(ActionMapping actionMapping,
                                 ActionForm actionForm,
                                 HttpServletRequest httpServletRequest,
                                 HttpServletResponse httpServletResponse) throws Exception {

        String serial = httpServletRequest.getParameter("serial");
        int manufacturerId = Integer.parseInt(httpServletRequest.getParameter("manufacturerId"));

        EquipmentItem item = equipmentItemService.getBySerialAndManufacturer(serial, manufacturerId);

        String result = "false";
        if (item!=null) {
            result="true";
        }

        httpServletResponse.setContentType("text/plain");
        httpServletResponse.getWriter().println(result);

        return null;
    }
}
